import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Sebastian
 * @version 2.0
 * @date 2024/7/1 20:50
 */
// 全排列II
    //https://leetcode.cn/problems/permutations-ii/
    // 区别在于存在重复数字
public class Solution47 {
    List<List<Integer>> result = new ArrayList<>();
    List<Integer> track = new ArrayList<>();
    public List<List<Integer>> permuteUnique(int[] nums) {
        boolean[] used = new boolean[nums.length];
        Arrays.fill(used, false);
        Arrays.sort(nums);
        backtrack(nums, used);
        return result;
    }

    private void backtrack(int[] nums, boolean[] used) {
        if (track.size() == nums.length) {
            result.add(new ArrayList<>(track));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false) {
                continue;
            }
            if (used[i] == false) {
                track.add(nums[i]);
                used[i] = true;
                backtrack(nums, used);
                used[i] = false;
                track.remove(track.size() - 1);
            }
        }
    }
}
